<template>
  <div class="home-view-user-login">
    <el-form class="home-view-form"
             :model="data"
             :rules="rules"
             ref="ruleForm">
      <el-form-item>
        <el-input class="home-view-form-input"
                  type="text"
                  v-model="data.username"
                  placeholder="请输入账号"/>
      </el-form-item>
      <el-form-item>
        <el-input class="home-view-form-input"
                  type="password"
                  v-model="data.password"
                  placeholder="请输入密码"/>
      </el-form-item>
      <el-button class="form-button"
                 @click="login('ruleForm')">登入
      </el-button>
    </el-form>
  </div>
</template>

<script>
import {userLogin} from "@/apis/common";

export default {

  components: {},
  props: {},
  data() {
    return {
      data: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          {required: true, message: "不能为空", trigger: "blur"},
        ],
        password: [
          {required: true, message: "不能为空", trigger: "blur"},
        ],
      }
    }
  },

  methods: {

    login(formName) {
      this.$refs[formName].validate(async (valid) => {
            if (valid) {
              userLogin(this.data).then(resp => {
                    if (resp?.data?.code === 1) {

                      // 跳转到主页面
                      // 将用户信息存储到localStorage中
                      localStorage.setItem("identity", resp?.data?.data?.identity)
                      localStorage.setItem("id", resp?.data?.data?.id)
                      localStorage.setItem("username", resp?.data?.data?.username)
                      localStorage.setItem("token", resp?.data?.data?.token)
                      localStorage.setItem("info_status", resp?.data?.data?.infoStatus)

                      this.$message.success("登录成功")
                      // 跳转页面
                      this.$router.push({name: 'home'}).catch(r => console.log(r))
                    } else {
                      this.$message.error(resp?.data?.msg)
                    }
                  }
              )
            } else {
              this.$message.error("登录失败，请稍后重试!")
              return false;
            }
          }
      )
      ;


    }
  },
}
</script>

<style scoped lang="scss">

.home-view-form {
  margin-top: 20px;

  .form-button {
    margin-top: 10%;
    width: 40%;
    margin-left: 30%;
  }
}

::v-deep .el-form-item {
  width: 80%;
  margin-left: 10%;

}

</style>